#!/bin/bash

#!/bin/bash
#description publish service

source /etc/init.d/functions

ENV="test"

PUBLISH_PS=''
PUBLISH_PID=0
checkpublish(){
  PUBLISH_PS=$(ps aux | grep 'publish.py' | grep -v 'grep')
  PUBLISH_PID=$(echo ${PUBLISH_PS} | awk '{print $2}')
}

start(){
  checkpublish
  if [ ! -z "$PUBLISH_PS" ];then
    action "publish service is started, pid: $PUBLISH_PID"
    return 0
  else
    if [ -f "/var/log/publish.log" ];then
      NOW=$(date "+%Y%m%d%H%M%S")
      echo "rename log file to publish.log.$NOW"
      mv /var/log/publish.log /var/log/publish.log.$NOW
    fi
    echo -n "publish service is starting ..."
    python3 -u /usr/etc/publish.py >> /var/log/publish.log 2>&1 &
    for i in {1..100};do
      started_log=$(grep "starting publish service" /var/log/publish.log)
      if [ ! -z "$started_log" ];then
        echo ""
        echo "$started_log"
        status
        return 0
      else
        sleep 2
        echo -n " ..."
      fi
    done
  fi
}

stop(){
  checkpublish
  if [ -z "$PUBLISH_PS" ];then
    action "publish service is stopped"
  else
    echo "stopping publish service (pid: $PUBLISH_PID) ..."
    kill -9 ${PUBLISH_PID}
    for i in {1..100};do
      checkpublish
      test -z "$PUBLISH_PS" && action "publish service is stopped" && return 0 || echo -n " ..."
      sleep 2
    done
  fi
}

status(){
  checkpublish
  if [ ! -z "$PUBLISH_PS" ];then
    action "publish service is running, pid: $PUBLISH_PID"
  else
    action "publish service is stopped" /bin/false
  fi
}


case $1 in
start)
    start
    ;;
stop)
    stop
    ;;
status)
    status
    ;;
restart)
    stop
    start
    ;;

*)
    echo "usage: publish status | stop | start | restart "
    ;;
esac